import { Button, Form, FormInstance, Input, Radio, Upload, UploadFile } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import React, { useEffect, useRef, useState } from "react";
import { RcFile, UploadProps } from "antd/lib/upload";
import { fileUpload, postCircleFriend, updateCircleFriend } from "@/redux/modules/circleFriend/action";
import useMessage from "@/hooks/useMessage";
import { RootState } from "@/redux";
import { useSelector } from "react-redux";
import { flushSync } from "react-dom";

interface PropsType {
	onComfirm?: () => void;
}

const CircleFriendEdit: React.FC<PropsType> = props => {
	const { TextArea } = Input;
	const { contextHolder, success } = useMessage();

	const circleFriendDetail = useSelector((state: RootState) => state.circleFriend.circleFriendDetail);

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	const handleUpload = async () => {
		const formData = new FormData();
		fileList.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await fileUpload(formData);
		return res;
	};

	const uploadProps: UploadProps = {
		onRemove: file => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: file => {
			flushSync(() => {
				setFileList([...fileList, file]);
			});
			return false;
		},
		fileList,
		multiple: true
	};

	const onFinish = async (values: any) => {
		let files;

		if (fileList.length > 0) {
			files = await handleUpload();
		}
		let form = {
			...values,
			...files,
			id: circleFriendDetail.id
		};
		updateCircleFriend(form);
		props.onComfirm && props.onComfirm();
		success("发布成功");
	};

	const formRef = useRef<FormInstance | null>(null);

	useEffect(() => {
		formRef.current?.resetFields();
	}, [circleFriendDetail, fileList]);

	useEffect(() => {
		return () => {
			formRef.current?.setFieldsValue({
				tag_name: "",
				tag_classify: ""
			});
		};
	});

	return (
		<>
			{contextHolder}
			<Form ref={formRef} labelCol={{ span: 4 }} layout="horizontal" onFinish={onFinish} initialValues={circleFriendDetail}>
				<Form.Item label="内容" rules={[{ required: true }]} name="content">
					<TextArea rows={4} />
				</Form.Item>
				<Form.Item label="置顶" name="top">
					<Radio.Group defaultValue={0}>
						<Radio value={0}> 否 </Radio>
						<Radio value={1}> 是 </Radio>
					</Radio.Group>
				</Form.Item>
				<Form.Item label="文件" valuePropName="fileList">
					<Upload listType="picture-card" {...uploadProps}>
						<div>
							<PlusOutlined />
							<div style={{ marginTop: 8 }}>上传文件</div>
						</div>
					</Upload>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</>
	);
};
export default CircleFriendEdit;
